<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>配置页面</title>
    <link rel="stylesheet" href="../../plugins/element-ui/index.css"/>
    <link rel="stylesheet" href="../../styles/config.css"/>
</head>
<body>
<div class="contain">
    <div id="app">
        <!-- 用户信息部分 -->
        <el-card shadow="hover" class="user-info-card">
            <h3 class="title">用户信息</h3>
            <el-descriptions :column="2" size="small">
                <el-descriptions-item label="用户名">{{ userInfo.name }}</el-descriptions-item>
                <el-descriptions-item label="角色">管理员</el-descriptions-item>
                <el-descriptions-item label="账号">{{ userInfo.username }}</el-descriptions-item>
                <el-descriptions-item label="修改密码">
                    <el-button type="primary" size="medium" @click="openChangePasswordDialog">修改密码</el-button>
                </el-descriptions-item>
            </el-descriptions>
        </el-card>

        <!-- 系统配置部分 -->
        <el-card shadow="hover" class="system-config-card">
            <h3 class="title">系统配置</h3>
            <el-descriptions :column="2" size="small">

                <!-- ID=1 数据源邮箱 -->
                <el-descriptions-item label="获取日报邮箱" style="line-height: 27px">
                    <el-row type="flex">
                        <el-col :span="18">
                            <span v-if="!isEditing.configEmail1">{{ systemConfig.configEmail1 }}</span>
                            <el-input v-if="isEditing.configEmail1" v-model="configForm.configEmail1" size="small"/>
                        </el-col>
                        <el-col :span="6">
                            <div v-if="!isEditing.configEmail1" class="button-group">
                                <el-button type="primary" size="mini" @click="toggleEdit('configEmail1')">修改
                                </el-button>
                            </div>
                            <div v-if="isEditing.configEmail1" class="button-group">
                                <el-button type="primary" size="mini" @click="confirmEdit('configEmail1')">确认
                                </el-button>
                                <el-button type="danger" size="mini" @click="cancelEdit('configEmail1')">取消
                                </el-button>
                            </div>
                        </el-col>
                    </el-row>
                </el-descriptions-item>

                <!-- ID=1 邮箱密钥 -->
                <el-descriptions-item label="邮箱密钥">
                    <el-row type="flex">
                        <el-col :span="18">
                            <span v-if="!isEditing.configSecretKey1"
                                  :style="{ maxWidth: '200px', display: 'inline-block', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }">
                                {{ showSecretKey1 ? systemConfig.configSecretKey1 : '********' }}
                            </span>
                            <el-input v-if="isEditing.configSecretKey1" v-model="configForm.configSecretKey1"
                                      size="small"/>
                        </el-col>
                        <el-col :span="6" class="icon-col">
                            <el-button type="text" size="mini" icon="el-icon-view"
                                       @click="toggleSecretKeyVisibility(1)"></el-button>
                        </el-col>
                        <el-col :span="6">
                            <div v-if="!isEditing.configSecretKey1" class="button-group">
                                <el-button type="primary" size="mini" @click="toggleEdit('configSecretKey1')">修改
                                </el-button>
                            </div>
                            <div v-if="isEditing.configSecretKey1" class="button-group">
                                <el-button type="primary" size="mini" @click="confirmEdit('configSecretKey1')">确认
                                </el-button>
                                <el-button type="danger" size="mini" @click="cancelEdit('configSecretKey1')">取消
                                </el-button>
                            </div>
                        </el-col>
                    </el-row>
                </el-descriptions-item>

                <!-- ID=2 数据源邮箱 -->
                <el-descriptions-item label="提醒邮件邮箱" style="line-height: 27px">
                    <el-row type="flex">
                        <el-col :span="18">
                            <span v-if="!isEditing.configEmail2">{{ systemConfig.configEmail2 }}</span>
                            <el-input v-if="isEditing.configEmail2" v-model="configForm.configEmail2" size="small"/>
                        </el-col>
                        <el-col :span="6">
                            <div v-if="!isEditing.configEmail2" class="button-group">
                                <el-button type="primary" size="mini" @click="toggleEdit('configEmail2')">修改
                                </el-button>
                            </div>
                            <div v-if="isEditing.configEmail2" class="button-group">
                                <el-button type="primary" size="mini" @click="confirmEdit('configEmail2')">确认
                                </el-button>
                                <el-button type="danger" size="mini" @click="cancelEdit('configEmail2')">取消
                                </el-button>
                            </div>
                        </el-col>
                    </el-row>
                </el-descriptions-item>

                <!-- ID=2 邮箱密钥 -->
                <el-descriptions-item label="邮箱密钥">
                    <el-row type="flex">
                        <el-col :span="18">
                            <span v-if="!isEditing.configSecretKey2"
                                  :style="{ maxWidth: '200px', display: 'inline-block', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }">
                                {{ showSecretKey2 ? systemConfig.configSecretKey2 : '********' }}
                            </span>
                            <el-input v-if="isEditing.configSecretKey2" v-model="configForm.configSecretKey2"
                                      size="small"/>
                        </el-col>
                        <el-col :span="6" class="icon-col">
                            <el-button type="text" size="mini" icon="el-icon-view"
                                       @click="toggleSecretKeyVisibility(2)"></el-button>
                        </el-col>
                        <el-col :span="6">
                            <div v-if="!isEditing.configSecretKey2" class="button-group">
                                <el-button type="primary" size="mini" @click="toggleEdit('configSecretKey2')">修改
                                </el-button>
                            </div>
                            <div v-if="isEditing.configSecretKey2" class="button-group">
                                <el-button type="primary" size="mini" @click="confirmEdit('configSecretKey2')">确认
                                </el-button>
                                <el-button type="danger" size="mini" @click="cancelEdit('configSecretKey2')">取消
                                </el-button>
                            </div>
                        </el-col>
                    </el-row>
                </el-descriptions-item>
            </el-descriptions>
            <el-button type="success" size="mini" @click="testConnection">测试连接</el-button>
        </el-card>

        <!-- 修改密码对话框 -->
        <!-- 修改密码对话框 -->
        <el-dialog :visible.sync="isPasswordDialogVisible" title="修改密码" width="400px"
                   :before-close="handleClosePasswordDialog">
            <el-form :model="passwordForm" ref="passwordForm" label-width="100px">
                <!-- 当前密码 -->
                <el-form-item label="当前密码" prop="oldPassword"
                              :rules="[{ required: true, message: '请输入当前密码', trigger: 'blur' }]">
                    <el-input v-model="passwordForm.oldPassword" show-password clearable></el-input>
                </el-form-item>

                <!-- 新密码 -->
                <el-form-item label="新密码" prop="newPassword"
                              :rules="[{ required: true, message: '请输入新密码', trigger: 'blur' }, { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }]">
                    <el-input v-model="passwordForm.newPassword" show-password clearable></el-input>
                </el-form-item>

                <!-- 确认密码 -->
                <el-form-item label="确认密码" prop="confirmPassword"
                              :rules="[{ required: true, message: '请确认新密码', trigger: 'blur' }, { validator: validateConfirmPassword, trigger: 'blur' }]">
                    <el-input v-model="passwordForm.confirmPassword" show-password clearable></el-input>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="closePasswordDialog">取消</el-button>
                <el-button type="primary" @click="submitPasswordChange">确认</el-button>
            </div>
        </el-dialog>


    </div>
</div>

<script src="../../plugins/vue/vue.js"></script>
<script src="../../plugins/element-ui/index.js"></script>
<script src="../../plugins/axios/axios.min.js"></script>
<script src="../../api/config.js"></script>
<script>
    new Vue({
        el: '#app',
        data() {
            return {
                userInfo: {},

                systemConfig: {
                    configEmail1: '',  // 用于 id=1 的邮箱
                    configSecretKey1: '',  // 用于 id=1 的密钥
                    configEmail2: '',  // 用于 id=2 的邮箱
                    configSecretKey2: '',  // 用于 id=2 的密钥
                },

                isEditing: {
                    configEmail1: false,
                    configSecretKey1: false,
                    configEmail2: false,
                    configSecretKey2: false,
                },

                configForm: {
                    configEmail1: '',
                    configSecretKey1: '',
                    configEmail2: '',
                    configSecretKey2: '',
                },

                isPasswordDialogVisible: false,  // 控制对话框的显示与隐藏
                isNewPasswordValid: false,  // 用于判断新密码是否满足长度要求
                passwordForm: {
                    oldPassword: '',
                    newPassword: '',
                    confirmPassword: ''
                },
                // 自定义的验证规则
                passwordRules: {
                    oldPassword: [{required: true, message: '请输入当前密码', trigger: 'blur'}],
                    newPassword: [
                        {required: true, message: '请输入新密码', trigger: 'blur'},
                        {min: 6, message: '密码长度不能少于6位', trigger: 'blur'},
                    ],
                    confirmPassword: [
                        {required: true, message: '请确认新密码', trigger: 'blur'},
                        {
                            validator: (rule, value, callback) => {
                                if (value !== this.passwordForm.newPassword) {
                                    callback(new Error('两次密码输入不一致'));
                                } else {
                                    callback();
                                }
                            }, trigger: 'blur'
                        },
                    ],
                },


                alertMessage: '',
                alertType: '',
                showSecretKey1: false, // 控制 ID=1 的密钥可见性
                showSecretKey2: false, // 控制 ID=2 的密钥可见性
            };
        },

        mounted() {
            const userInfo = window.localStorage.getItem('userInfo')
            if (userInfo) {
                this.userInfo = JSON.parse(userInfo)
            }
            this.getSystemConfig(1);
            this.getSystemConfig(2); // 获取 ID 为 2 的配置
        },

        methods: {
            // 获取用户信息
            async getUserInfo() {
                const userInfo = {
                    userId: 123,
                    username: 'admin',
                }
                try {
                    await getUserInfo(userInfo).then(response => {
                        this.userInfo = response.data;
                    })
                } catch (error) {
                    console.error(error);
                }
            },

            async testConnection() {
                try {
                    const response = await fetch('/conn_email', {
                        method: 'GET', // 使用 GET 方法
                        headers: {
                            'Content-Type': 'application/json',
                        },
                    });

                    // 检查响应状态
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }

                    const data = await response.json(); // 解析 JSON 响应

                    // 根据 status 显示通知
                    if (data.status === 'success') {
                        this.$notify({
                            title: '成功',
                            message: data.msg,
                            type: 'success',
                        });
                    } else {
                        this.$notify({
                            title: '失败',
                            message: data.msg || '连接失败，请重试。',
                            type: 'error',
                        });
                    }
                } catch (error) {
                    this.$notify({
                        title: '错误',
                        message: error.message || '发生了一个错误，请重试。',
                        type: 'error',
                    });
                }
            },

            //获取系统配置
            async getSystemConfig(id) {
                try {
                    const response = await getSysConfig(id); // 发送请求以获取指定 ID 的配置
                    if (id === 1) {
                        // 更新 ID=1 的配置
                        this.systemConfig.configEmail1 = response.data.configEmail; // 使用 configEmail1
                        this.systemConfig.configSecretKey1 = response.data.configSecretKey; // 使用 configSecretKey1
                    } else if (id === 2) {
                        // 更新 ID=2 的配置
                        this.systemConfig.configEmail2 = response.data.configEmail; // 使用 configEmail2
                        this.systemConfig.configSecretKey2 = response.data.configSecretKey; // 使用 configSecretKey2
                    }
                } catch (error) {
                    this.alertMessage = '获取系统配置失败';
                }
            },

            toggleSecretKeyVisibility(id) {
                if (id === 1) {
                    this.showSecretKey1 = !this.showSecretKey1; // 切换 ID=1 的密钥可见性
                } else if (id === 2) {
                    this.showSecretKey2 = !this.showSecretKey2; // 切换 ID=2 的密钥可见性
                }
            },

            openChangePasswordDialog() {
                this.isPasswordDialogVisible = true;
            },

            // 关闭对话框
            closePasswordDialog() {
                this.isPasswordDialogVisible = false;
                this.resetPasswordForm();
            },
            // 重置表单
            resetPasswordForm() {
                this.passwordForm.oldPassword = '';
                this.passwordForm.newPassword = '';
                this.passwordForm.confirmPassword = '';
                this.$refs.passwordForm.resetFields();
            },


            // 提交密码修改
            submitPasswordChange() {
                this.$refs.passwordForm.validate(async (valid) => {
                    if (!valid) {
                        this.$message.error('请检查表单中的错误');
                        return;
                    }

                    // 模拟后端请求参数
                    const password = {
                        id: this.userInfo.id,
                        oldPassword: this.passwordForm.oldPassword,
                        newPassword: this.passwordForm.newPassword,
                    };

                    try {
                        await updatePassword(password).then(response => {
                            if (response.status === 'success') {
                                this.$message.success('密码修改成功');
                                this.closePasswordDialog();
                            } else {
                                this.$message.error(response.data.message || '密码修改失败');
                            }
                        });
                    } catch (error) {
                        this.$message.error('请求失败，请稍后重试');
                    }
                });
            },

            // 自定义确认密码的校验逻辑
            validateConfirmPassword(rule, value, callback) {
                if (value === '') {
                    callback(new Error('请确认新密码'));
                } else if (value !== this.passwordForm.newPassword) {
                    callback(new Error('两次密码输入不一致'));
                } else {
                    callback();
                }
            },

            toggleEdit(field) {
                this.isEditing[field] = true;
                this.configForm[field] = this.systemConfig[field];
            },

            validateField(field, value) {
                if (field === 'configEmail1' || field === 'configEmail2') {
                    if (!this.isValidEmail(value)) {
                        this.alertMessage = '邮箱格式不正确';
                        this.alertType = 'error';
                        return false;
                    }
                }
                if (field === 'configSecretKey1' || field === 'configSecretKey2') {
                    // 检查 value 是否存在且为字符串
                    if (typeof value !== 'string' || value.trim() === '') {
                        this.alertMessage = '密钥不能为空';
                        this.alertType = 'error';
                        return false;
                    }
                }
                return true;
            },

            async confirmEdit(field) {
                // 验证字段
                if (!this.validateField(field, this.configForm[field])) {
                    return; // 如果验证失败，则返回
                }

                let id = field.endsWith('1') ? 1 : 2; // 根据 field 确定 ID
                let updateField = field.startsWith('configEmail') ? 'configEmail' : 'configSecretKey'; // 确定更新类型

                // 创建请求体
                const requestData = {
                    id: id,
                    type: updateField,
                    value: this.configForm[field] // 传入相应的值
                };

                console.log("打印请求数据", requestData);

                try {
                    // 向后端发送更新请求
                    const response = await updateDataSource(requestData);
                    if (response.status === "success") {
                        // 根据 ID 更新系统配置
                        if (updateField === 'configEmail') {
                            this.systemConfig[`configEmail${id}`] = response.data.email; // 更新对应的邮箱
                        } else if (updateField === 'configSecretKey') {
                            this.systemConfig[`configSecretKey${id}`] = response.data.secretKey; // 更新对应的密钥
                        }
                    }
                } catch (error) {
                    console.error(error);
                }

                this.isEditing[field] = false; // 结束编辑状态
                this.alertMessage = `${updateField === 'email' ? '邮箱' : '密钥'}修改成功！`;
                this.alertType = 'success'; // 提示成功
            },

            cancelEdit(field) {
                this.isEditing[field] = false;
            },

            isValidEmail(email) {
                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                return emailRegex.test(email);
            },
            // 关闭对话框时重置表单内容
            handleClosePasswordDialog(done) {
                this.closePasswordDialog();
                done(); // 继续关闭对话框
            }
        },
    })
    ;
</script>
</body>
</html>
